//
//  ShowSearchVC.m
//  LazyCat
//
//  Created by linhui on 15/12/16.
//  Copyright (c) 2015年 zhanshu. All rights reserved.
//

#import "ShowSearchVC.h"
#import "OrderCell.h"
#import "MJChiBaoZiHeader.h"
#import "DetailOrderVC.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "MSBluetoothManager.h"
#import "OrderViewController.h"
#import "CanceOrderlViewController.h"
@interface ShowSearchVC ()<UITableViewDataSource,UITableViewDelegate,backDelegate>
{
    UITableView *_tableView;
    NSMutableArray *_dataArray;
    UIView *_backTView;//没订单时背部提醒
    NSString * _urlIndex;//起始页
    BOOL _isLoading;
    NSString *_totalCount;//总页数
    NSDictionary *dataDic;
    NSString *_teleStr;
    NSString *_order;
    NSString *_name;
}
@property (nonatomic, retain) CBCentralManager *centralManager;
@property (nonatomic, retain) CBPeripheral *p;
@property (nonatomic, retain) CBCharacteristic * c;

@property (nonatomic, retain) NSString *UUID;


@property (nonatomic, retain) NSMutableArray *peripheralArray;
@property (nonatomic, retain) NSMutableArray *blueNameArr;
@end

@implementation ShowSearchVC
-(void)backStr:(NSString *)str {
    if ([str isEqualToString:@"TTT"]) {
        [self loadData];
    }
}
- (void)touchesBegan
{
    NSString *RStr = @"2764";
    NSMutableString *str = [NSMutableString new];
    [str appendFormat:@"%c", 28];
    [str appendFormat:@"%c", 33];
    [str appendFormat:@"%c", 8];
    
    [[MSBluetoothManager shareInstance].cbPeripheral writeValue:[str dataUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)] forCharacteristic:[MSBluetoothManager shareInstance].cbCharacteristcs type:CBCharacteristicWriteWithResponse];
    NSString *shopName = [ShopCommonModel share].shopname; // 商家名称
    NSString *orderno = [dataDic objectForKey:@"orderno"]; // 订单号
    NSString *createtime = [dataDic objectForKey:@"createtime"]; // 下单时间
    NSString *sendtime = [dataDic objectForKey:@"sendtime"]; // 配送时间
    NSString *mobile = [dataDic objectForKey:@"mobile"]; // 联系电话
    NSString *address = [dataDic objectForKey:@"address"]; // 联系地址
    NSArray *temArr = [dataDic objectForKey:@"products"]; // 商品数组
    NSString *totalmoney = [dataDic objectForKey:@"totalmoney"]; // 总金额
    NSString *productsnum = [dataDic objectForKey:@"productsnum"]; // 商品数量
    NSString *paytypestr = [dataDic objectForKey:@"paytypestr"]; // 支付方式
    
    NSString *product = @"";
    for (int i = 0; i < temArr.count; i++) {
        NSString *pName = [temArr[i] objectForKey:@"productname"]; // 商品名字
        NSString *price = [temArr[i] objectForKey:@"price"]; // 商品价格
        NSString *numbuy = [temArr[i] objectForKey:@"numbuy"]; // 商品价格
        product = [NSString stringWithFormat:@"%@\n%@\n                x%@       %@\n",product,pName,numbuy,price];
        
    }
    
    
    //    RStr = @"杜博 你好呀!!!\n我很好\n啦啦啦\n啦啦啦\n啦啦\n啦啦啦\n啦啦啦\n啦啦\n";
    RStr = [NSString stringWithFormat:@"\n商家名称:%@\n订单号:%@\n下单时间:%@\n配送时间:%@\n联系电话:%@\n支付方式:%@\n联系地址:%@\n------------------------------\n商品名称       数量      金额\n------------------------------\n%@\n------------------------------\n商品总数量:%@\n消费总金额:%@\n------------------------------\n 懒猫社长\n\n\n",shopName,orderno,createtime,sendtime,mobile,paytypestr,address,product,productsnum,totalmoney];
    
    NSData *nsdata =  [RStr dataUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)];
    [[MSBluetoothManager shareInstance] writeData:nsdata];
    
}
- (void)initNav:(NSString *)title doBack:(BOOL)doBack {
    [super initNav:title doBack:YES];
    self.navBar.hidden=NO;
    self.title=title;
    if (doBack) {
        UIButton * backBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        backBtn.frame=CGRectMake(8, 20+(44-21)/2, 12, 21);
        [backBtn setNormalImageWith:@"backimg"];
        [backBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
        [backBtn setHitTestEdgeInsets:UIEdgeInsetsMake(-10, -14, -14, -25)];
        [self.navBar addSubview:backBtn];
    }
}
- (void)backAction:(UIButton *)btn{
    NSArray * viewC = self.navigationController.viewControllers;
    [self.navigationController popToViewController:[viewC objectAtIndex:1] animated:YES];
}
-(void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    [self loadData];
//    [self addRefresh];
    [self loadMore];
}

- (void)createUI {
    [self initNav:@"订单搜索" doBack:YES];
    self.view.backgroundColor = BackColor;
    self.automaticallyAdjustsScrollViewInsets = NO;
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 65, ScreenWidth, ScreenHeight - 64)];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator = NO;
    _backTView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64)];
    [self.view addSubview:_tableView];
    _backTView.backgroundColor = BackColor;
    _backTView.hidden = YES;
    [_tableView addSubview:_backTView];
    
    _tableView.header = [MJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(addRefresh)];
    
    UIImageView *backImage = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenWidth - 80)/2, 100, 80, 90)];
    backImage.image = [UIImage imageNamed:@"noSearch"];
    [_backTView addSubview:backImage];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake((ScreenWidth - 200)/2, backImage.frame.origin.y + 90, 200, 50)];
    label.textColor = SetColor(153, 153, 153, 1);
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"抱歉，没有找到相关订单";
    [_backTView addSubview:label];
    _dataArray = [[NSMutableArray alloc]init];
    _urlIndex = @"1";
    _isLoading = NO;
//    _loading = [[FeWifiManHub alloc] initWithView:self.view withMode:FeWifiManHubModeOnlyLoader];
//    _loading.frame = CGRectMake(_loading.frame.origin.x, _loading.frame.origin.y - 104, _loading.frame.size.width, _loading.frame.size.height);
//    [self.view addSubview:_loading];
//    [_loading show];
    
}
- (void)prepareForData {
    
}
- (void)loadData {
    if (self.keyWord == nil) {
        self.keyWord = @"";
    }
    NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults];
    NSString *cid = [userDefaul objectForKey:@"cid"];
    NSString *kUrl;
    kUrl = [NSString stringWithFormat:OrderUrl,@"15",_urlIndex,[AppData share].username,@"",@"",@"",cid,self.keyWord];
    if ([_urlIndex isEqualToString:@"1"]) {
        [_dataArray removeAllObjects];
    }
    [NTNetUtil sendRequestWithUrl:kUrl requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
        NSDictionary *dic = networkRequest.responseData;
        NSLog(@"%@",networkRequest.responseData);
        
        NSLog(@"error:%@",error);
        _totalCount = [[dic objectForKey:@"page"] objectForKey:@"totalpage"];
        NSArray *arr = [dic objectForKey:@"d"];
        [_dataArray addObjectsFromArray:arr];
        _isLoading = NO;
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
        //[_loading dismiss];
        
        //[_loading removeFromSuperview];
        if ([_totalCount isEqualToString:@"0"] || _totalCount == nil) {
            _backTView.hidden = NO;
        }else {
            _backTView.hidden = YES;
        }
        [_tableView reloadData];
    }];
    
    
}
- (void)addRefresh {
    if (_isLoading) {
        return;
    }
    _isLoading = YES;
//    MJChiBaoZiHeader *header = [MJChiBaoZiHeader headerWithRefreshingBlock:^{
    _urlIndex = @"1";
//        [header beginRefreshing];
    [self loadData];
    [_tableView.header endRefreshing];
//    }];
//    _tableView.header = header;
//    header.lastUpdatedTimeLabel.hidden = YES;
}
- (void)loadMore {
    if (_isLoading) {
        return;
    }
    _isLoading = YES;
    MJRefreshAutoFooter *foot = [MJRefreshAutoFooter footerWithRefreshingBlock:^{
        if ([_urlIndex integerValue] >= [_totalCount integerValue]) {
            [[MessShowView share]showWithMess:@"没有更多数据"];
            return ;
        }
        _urlIndex = [NSString stringWithFormat:@"%ld",[_urlIndex integerValue]+1];
        [foot beginRefreshing];
        [self loadData];
        
    }];
    _tableView.footer = foot;
}
- (void)btnClick:(UIButton *)sender event:(id)event {
    //取indexpath
    NSSet *touches =[event allTouches];
    UITouch *touch =[touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:_tableView];
    NSIndexPath *indexPath= [_tableView indexPathForRowAtPoint:currentTouchPosition];
    if (indexPath!= nil)
    {
        if (indexPath.row < [_dataArray count]){
            _order = [_dataArray[indexPath.row] objectForKey:@"orderno"];
        }
        _name = [AppData share].username;
        if (sender.tag == 332) {//取消订单
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"确认取消" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
            alert.tag = 501;
            [alert show];
        }else if (sender.tag == 333) {//订单发货
            UIAlertView *fahuoAlert = [[UIAlertView alloc]initWithTitle:nil message:@"确认发货" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
            fahuoAlert.tag = 502;
            [fahuoAlert show];
            
        }else if (sender.tag == 334){ // 打印小票
            dataDic = [NSDictionary dictionary];
            dataDic =  _dataArray[indexPath.row];
            [self touchesBegan];
        }else if (sender.tag == 335){//联系买家
            
            NSString *mobile = [_dataArray[indexPath.row] objectForKey:@"mobile"];
            NSString *user = [_dataArray[indexPath.row]objectForKey:@"linkman"];
            NSMutableString * str1=[[NSMutableString alloc] initWithFormat:@"tel://%@",mobile];
            _teleStr = str1;
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:[NSString stringWithFormat:@"买家姓名:%@\n联系电话：%@\n是否通话？",user,mobile] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alert.tag = 503;
            [alert show];
        }
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 501) {
        if (buttonIndex == 1) {
        CanceOrderlViewController *cancel = [[CanceOrderlViewController alloc]init];
        cancel.orderNumber = _order;
        cancel.orderType = @"0";
        cancel.delegate = self;
        [self.navigationController pushViewController:cancel animated:YES];
        }
    }else if (alertView.tag == 503) {
        if (buttonIndex == 1) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:_teleStr]];
        }else {
            return;
        }
    }else if (alertView.tag == 502){
        if (buttonIndex == 1) {
            NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults];
            NSString *cid = [userDefaul objectForKey:@"cid"];
            NSString *url = [NSString stringWithFormat:fahuoOrder,_order,_name,cid];
            [NTNetUtil sendRequestWithUrl:url requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
                NSDictionary *dic = networkRequest.responseData;
                NSString *result = [dic objectForKey:@"m"];
                
                if ([result isEqualToString:@"success"]) {
                    [[MessShowView share]showWithMess:@"订单发货成功" login:YES];
                    [self loadData];
                }
                [_tableView reloadData];
            }];
        }
    }
    
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"orderCell"];
    cell = nil;
    if (cell == nil) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"OrderCell" owner:nil options:nil][0];
    }
    [cell.deFa addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];
    [cell.daYin addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];
    [cell.lianXi addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];
    [cell.quXiao addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];
    [cell.backQuxiaoBtn addTarget:self action:@selector(btnClick:event:) forControlEvents:UIControlEventTouchUpInside];
    cell.backgroundColor = BackColor;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //NSDictionary *products = [_dataArray[indexPath.row] objectForKey:@"products"][0];
    //产品数组
    if (indexPath.row < [_dataArray count]) {////////防止数组越界
        NSArray *productsArr = [_dataArray[indexPath.row] objectForKey:@"products"];
        
        for (int i = 0; i < productsArr.count; i ++) {
            if (i==0) {
                UIImageView *imageView = (UIImageView *)[cell viewWithTag:100+i];
                [imageView sd_setImageWithURL:[NSURL URLWithString:[productsArr[i] objectForKey:@"img"]]];
            }else if (i>=1&&i==1){
                UIImageView *imageView = (UIImageView *)[cell viewWithTag:100+i];
                [imageView sd_setImageWithURL:[NSURL URLWithString:[productsArr[i] objectForKey:@"img"]]];
            }else if (i==2){
                UIImageView *imageView = (UIImageView *)[cell viewWithTag:100+i];
                [imageView sd_setImageWithURL:[NSURL URLWithString:[productsArr[i] objectForKey:@"img"]]];
            }else if (i==3){
                UIImageView *imageView = (UIImageView *)[cell viewWithTag:100+i];
                [imageView sd_setImageWithURL:[NSURL URLWithString:[productsArr[i] objectForKey:@"img"]]];
            }else if (i==4){
                UIImageView *imageView = (UIImageView *)[cell viewWithTag:100+i];
                [imageView sd_setImageWithURL:[NSURL URLWithString:[productsArr[i] objectForKey:@"img"]]];
            }else if (i==5){
                UIImageView *imageView = (UIImageView *)[cell viewWithTag:100+i];
                [imageView sd_setImageWithURL:[NSURL URLWithString:[productsArr[i] objectForKey:@"img"]]];
            }
        }/////
        //"isdisplaycancelorderbutton": "1",//是否显示取消订单按钮
        //"isdisplayfahuobutton": "0",//是否显示发货按钮
        NSString *isCancelShow = [_dataArray[indexPath.row] objectForKey:@"isdisplaycancelorderbutton"];
        NSString *isFahuoShow = [_dataArray[indexPath.row] objectForKey:@"isdisplayfahuobutton"];
        if ([isCancelShow isEqualToString:@"0"]) {
            cell.quXiao.hidden = YES;
        }
        if ([isFahuoShow isEqualToString:@"0"]) {
            cell.deFa.hidden = YES;
            if ([isCancelShow isEqualToString:@"1"]) {
                cell.quXiao.hidden = YES;
                cell.backQuxiaoBtn.hidden = NO;
            }
        }
        cell.deseLabel.text = [productsArr[0] objectForKey:@"productname"];
        cell.moneyLabel.text = [NSString stringWithFormat:@"¥%@",[productsArr[0] objectForKey:@"price"]];
        cell.countLabel.text = [NSString stringWithFormat:@"x%@",[productsArr[0] objectForKey:@"numbuy"]];
        if (productsArr.count>1) {
            cell.deseLabel.hidden = YES;
            cell.moneyLabel.hidden = YES;
            cell.countLabel.hidden = YES;
        }
        cell.orderNumLabel.text = [NSString stringWithFormat:@"订单号:%@",[_dataArray[indexPath.row] objectForKey:@"orderno"]];
        cell.statuesLabel.text = [_dataArray[indexPath.row] objectForKey:@"orderstatustext"];
        [cell.InBtn addTarget:self action:@selector(inBtnClicl:event:) forControlEvents:UIControlEventTouchUpInside];
        if ([[_dataArray[indexPath.row]objectForKey:@"iscod"] isEqualToString:@"1"]) {
            cell.huodaofukuanLabel.text = @"货到付款";
        }
        //cell.statuesLabel.textColor = SetColor(255,179, 14, 1);
        cell.sendTimeLabel.text = [NSString stringWithFormat:@"下单时间:%@",[_dataArray[indexPath.row] objectForKey:@"createtime"]]
        ;
        //cell.sendTimeLabel.textColor = SetColor(153, 153, 153, 1);
        cell.sumContentLabel.text = [NSString stringWithFormat:@"共%@件商品 合计¥%@ (含运费¥%@)",[_dataArray[indexPath.row] objectForKey:@"productsnum"],[_dataArray[indexPath.row] objectForKey:@"totalmoney"],[_dataArray[indexPath.row] objectForKey:@"addservicefee"]];
        
//        if ([[_dataArray[indexPath.row] objectForKey:@"sendtimerang"]isEqualToString:@""]) {
//            cell.xiaDanTimeLabel.text = @"配送时间:立即配送";
//        }else {
//            cell.xiaDanTimeLabel.text = [NSString stringWithFormat:@"配送时间：%@",[_dataArray[indexPath.row] objectForKey:@"sendtimerang"]];
//        }
        //cell.countLabel.textColor = SetColor(153, 153, 153, 1);
        if (_dataArray.count == 0) {
            _backTView.hidden = NO;
        }
    }
    return cell;

}
- (void)inBtnClicl:(UIButton *)sender event:(id)event{
    NSSet *touches =[event allTouches];
    UITouch *touch =[touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:_tableView];
    NSIndexPath *indexPath= [_tableView indexPathForRowAtPoint:currentTouchPosition];
    if (kNetworkNotReachability) { // 没网
        [[MessShowView share] showWithMess:@"当前网络不给力"];
        return;
    }else {
    NSString *isCancelShow = [_dataArray[indexPath.row] objectForKey:@"isdisplaycancelorderbutton"];
    NSString *isFahuoShow = [_dataArray[indexPath.row] objectForKey:@"isdisplayfahuobutton"];
    NSString *isYanShi = [_dataArray[indexPath.row]objectForKey:@"isdisplaydelaysendgoodsbutton"];
    DetailOrderVC *detail = [[DetailOrderVC alloc]init];
    detail.orderNum = [_dataArray[indexPath.row] objectForKey:@"orderno"];
    detail.dataArrray = _dataArray[indexPath.row];
    detail.quxiao = isCancelShow;
    detail.fahuo = isFahuoShow;
    detail.yanshi = @"0";
    [self.navigationController pushViewController:detail animated:YES];
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 200;
}
@end
